/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package classes;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Alvaro Los datos que aparecen en esta clase pertencen todos la tabla
 * user. Cada clase representara a una tabla
 */
public class user {

    private int id;
    String name;
    String secondname;
    String email;
    float money;
    String country;
    String city;
    String zip;
    String street;
    String number;
    String floor;
    String letter;
    String pass;
    String dir;
    int purchases;

    public user(String name, String secondname, String email, float money, String country, String city, String zip, String street, String number, String floor, String letter, String pass, String dir, int purchases) {
        this.name = name;
        this.secondname = secondname;
        this.email = email;
        this.money = money;
        this.country = country;
        this.city = city;
        this.zip = zip;
        this.street = street;
        this.number = number;
        this.floor = floor;
        this.letter = letter;
        this.pass = pass;
        this.dir = dir;
        this.purchases = purchases;
    }

    public user() {
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getDir() {
        return dir;
    }

    public void setDir(String dir) {
        this.dir = dir;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFloor() {
        return floor;
    }

    public void setFloor(String floor) {
        this.floor = floor;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getLetter() {
        return letter;
    }

    public void setLetter(String letter) {
        this.letter = letter;
    }

    public float getMoney() {
        return money;
    }

    public void setMoney(float money) {
        this.money = money;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    public String getSecondname() {
        return secondname;
    }

    public void setSecondname(String secondname) {
        this.secondname = secondname;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    public int getPurchases() {
        return purchases;
    }

    public void setPurchases(int purchases) {
        this.purchases = purchases;
    }

    /**
     * ************ DB *************************
     */
    public boolean guardar() throws SQLException {


        System.out.println("Email del registro: " + email);
        ObjetoDB o = new ObjetoDB();

        String cash = Float.toString(money);
        String purch = Integer.toString(purchases);

        o.setTabla("user");
        o.addCampo("name", name);
        o.addCampo("secondname", secondname);
        o.addCampo("email", email);
        o.addCampo("money", cash);
        o.addCampo("country", country);
        o.addCampo("city", city);
        o.addCampo("zip", zip);
        o.addCampo("street", street);
        o.addCampo("number", number);
        o.addCampo("floor", floor);
        o.addCampo("letter", letter);
        o.addCampo("pass", pass);
        o.addCampo("dir", dir);
        o.addCampo("purchases", purch);

        AdminDB adb = new AdminDB();
        return adb.guardar(o);

    }

    public void getByEmail(Connection conn, String email) throws SQLException {
        ResultSet rset = null;
        try {
            PreparedStatement stmt = null;

            if (null == stmt) {
                stmt = conn.prepareStatement("SELECT * FROM `F1shopOnline`.`user` WHERE email='" + email + "';");
                System.out.println("Listado de usuarios por email...");
            }
            rset = stmt.executeQuery();

            if (rset.next()) {

                this.setId(rset.getInt("ID"));
                this.name = rset.getString("name");
                this.secondname = rset.getString("secondname");
                this.email = rset.getString("email");
                this.country = rset.getString("country");
                this.city = rset.getString("city");
                this.zip = rset.getString("zip");
                this.street = rset.getString("street");
                this.number = rset.getString("number");
                this.floor = rset.getString("floor");
                this.letter = rset.getString("letter");
                this.pass = rset.getString("pass");
                this.dir = rset.getString("dir");

            }

            if (stmt != null) {
                stmt.close();
            }

        } catch (SQLException e) {
            System.out.println("Error de MySQL: " + e.getMessage());
        } catch (Exception e) {
            Logger.getLogger("GetbyEmail").log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());
        } finally {
            if (rset != null) {
                try {
                    rset.close();
                } catch (SQLException e) {
                    Logger.getLogger("GetbyEmail").log(Level.SEVERE, "ERROR AL CERRAR RSET: " + e.getLocalizedMessage());
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    Logger.getLogger("GetbyEmail").log(Level.SEVERE, "ERROR AL CERRAR LA CONEXION: " + e.getLocalizedMessage());
                }
            }
        }
    }

    public boolean borrar(String email) throws SQLException {//En teoria iria son pasarle el email
        AdminDB adb = new AdminDB();

        int cpID = adb.getID("user", "email='" + email + "'");

        ObjetoDB o = new ObjetoDB();
        o.setTabla("user");
        o.addCampo("email", email);
        return adb.borrar(o);

    }

    public boolean borrarTodosUsuarios() throws SQLException {
        AdminDB adb = new AdminDB();
        ObjetoDB o = new ObjetoDB();
        o.setTabla("user");
        return adb.vaciarTabla(o);
    }

    public List<user> getAllUsuarios(Connection conn) throws SQLException {
        ResultSet rset = null;
        try {
            PreparedStatement stmt = null;
            if (null == stmt) {
                stmt = conn.prepareStatement("SELECT * FROM `F1shopOnline`.`user`");
            }
            rset = stmt.executeQuery();
            List<user> users = new ArrayList<user>();
            while (rset.next()) {
                user c = new user();
                c.setId(rset.getInt("ID"));
                c.setName(rset.getString("name"));
                c.setSecondname(rset.getString("secondname"));
                c.setEmail(rset.getString("email"));
                c.setCountry(rset.getString("country"));
                c.setCity(rset.getString("city"));
                c.setZip(rset.getString("zip"));
                c.setStreet(rset.getString("street"));
                c.setNumber(rset.getString("number"));
                c.setFloor(rset.getString("floor"));
                c.setDir(rset.getString("dir"));
                users.add(c);
            }
            if (stmt != null) {
                stmt.close();
            }
            return users;

        } catch (SQLException e) {
            System.out.println("Error de MySQL: " + e.getMessage());
            return null;
        } catch (Exception e) {
            Logger.getLogger("Cliente").log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());
            return null;
        } finally {
            if (rset != null) {
                try {
                    rset.close();
                } catch (SQLException e) {
                    Logger.getLogger("GetAllUsuarios").log(Level.SEVERE, "ERROR AL CERRAR RSET: " + e.getLocalizedMessage());
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    Logger.getLogger("GetAllUsuarios").log(Level.SEVERE, "ERROR AL CERRAR LA CONEXION: " + e.getLocalizedMessage());
                }
            }
        }
    }

    public List<user> searchUsers(Connection conn, String busqueda, String by) throws SQLException {
        ResultSet rset = null;
        try {
            PreparedStatement stmt = null;
            if (null == stmt) {
                stmt = conn.prepareStatement("SELECT * FROM `F1shopOnline`.`user` WHERE " + by + " LIKE '%" + busqueda + "%'");
            }
            rset = stmt.executeQuery();
            List<user> users = new ArrayList<user>();
            while (rset.next()) {
                user c = new user();
                c.setId(rset.getInt("ID"));
                c.setName(rset.getString("name"));
                c.setSecondname(rset.getString("secondname"));
                c.setEmail(rset.getString("email"));
                c.setPass(rset.getString("pass"));
                c.setCountry(rset.getString("country"));
                c.setCity(rset.getString("city"));
                c.setZip(rset.getString("zip"));
                c.setStreet(rset.getString("street"));
                c.setNumber(rset.getString("number"));
                c.setLetter(rset.getString("letter"));
                c.setFloor(rset.getString("floor"));
                c.setDir(rset.getString("dir"));
                c.setMoney(rset.getFloat("money"));
                users.add(c);
            }

            if (stmt != null) {
                stmt.close();
            }
            return users;

        } catch (SQLException e) {
            System.out.println("Error de MySQL: " + e.getMessage());
            return null;
        } catch (Exception e) {
            Logger.getLogger("Cliente").log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());
            return null;
        } finally {
            if (rset != null) {
                try {
                    rset.close();
                } catch (SQLException e) {
                    Logger.getLogger("SearchUsers").log(Level.SEVERE, "ERROR AL CERRAR RSET: " + e.getLocalizedMessage());
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    Logger.getLogger("SearchUsers").log(Level.SEVERE, "ERROR AL CERRAR LA CONEXION: " + e.getLocalizedMessage());
                }
            }
        }
    }

    public boolean changePasswordInfo(Connection conn, String email, String oldpass, String newpass) throws SQLException {
        try {
            PreparedStatement stmt = null;

            if (null == stmt) {
                stmt = conn.prepareStatement("UPDATE `F1shopOnline`.`user` SET pass='" + newpass + "' WHERE email='" + email + "' AND pass='" + oldpass + "'");
                System.out.println(email + " esta cambiando su password.");
            }

            stmt.executeUpdate();


            stmt.close();

            return true;
        } catch (SQLException e) {
            System.out.println("Error de MySQL: " + e.getMessage());
        } catch (Exception e) {
            Logger.getLogger("ChangePasswordInfo").log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());
            System.out.println("Error inesperado: " + e.getMessage());
        } finally {

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    Logger.getLogger("ChangePassword").log(Level.SEVERE, "ERROR AL CERRAR LA CONEXION: " + e.getLocalizedMessage());
                }
            }
        }
        return false;
    }

    public boolean changePersonalInfo(Connection conn, String name, String secondname, String email, String email_old) throws SQLException {
        try {
            PreparedStatement stmt = null;

            if (null == stmt) {
                stmt = conn.prepareStatement("UPDATE user SET name='" + name + "', secondname='" + secondname + "', email='" + email + "' WHERE email='" + email_old + "'");
                System.out.println(email + " esta cambiando su informacion.");
            }

            stmt.executeUpdate();
            stmt.close();

            return true;
        } catch (SQLException e) {
            System.out.println("Error de MySQL: " + e.getMessage());
        } catch (Exception e) {
            Logger.getLogger("ChangePersonalInfo").log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());
            System.out.println("Error inesperado: " + e.getMessage());
        } finally {

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    Logger.getLogger("ChangePersonalInfo").log(Level.SEVERE, "ERROR AL CERRAR LA CONEXION: " + e.getLocalizedMessage());
                }
            }
        }
        return false;
    }

    public boolean changeShipInfo(Connection conn, String country, String city, String street, String zip, String number, String floor, String letter, String email) throws SQLException {
        try {
            PreparedStatement stmt = null;

            if (null == stmt) {
                stmt = conn.prepareStatement("UPDATE user SET country='" + country + "', city='" + city + "', zip='" + zip + "', street='" + street + "', number='" + number + "'"
                        + ", floor='" + floor + "', letter='" + letter + "' WHERE email='" + email + "'");
                System.out.println(email + " esta cambiando su direccion.");
            }
            stmt.executeUpdate();
            stmt.close();
            return true;
        } catch (SQLException e) {
            System.out.println("Error de MySQL: " + e.getMessage());
        } catch (Exception e) {
            Logger.getLogger("ChangeShipInfo").log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());

            System.out.println("Error inesperado: " + e.getMessage());
        } finally {

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    Logger.getLogger("ChangeShipInfo").log(Level.SEVERE, "ERROR AL CERRAR LA CONEXION: " + e.getLocalizedMessage());
                }
            }
        }
        return false;
    }

    public void changePhoto(Connection conn, String fileName, String email) throws SQLException {
        try {
            PreparedStatement stmt = null;

            if (null == stmt) {
                stmt = conn.prepareStatement("UPDATE user SET dir='images/userphotos/" + fileName + "' WHERE email='" + email + "'");
                System.out.println(email + " esta cambiando su foto de usuario.");
            }

            stmt.executeUpdate();
            stmt.close();
        } catch (SQLException e) {
            System.out.println("Error de MySQL: " + e.getMessage());
        } catch (Exception e) {
            Logger.getLogger("ChangePhoto").log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());
            System.out.println("Error inesperado: " + e.getMessage());
        } finally {

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    Logger.getLogger("ChangePhoto").log(Level.SEVERE, "ERROR AL CERRAR LA CONEXION: " + e.getLocalizedMessage());
                }
            }

        }
    }

    public String recoverName(Connection conn, String email) throws SQLException {
        ResultSet rset = null;
        try {

            PreparedStatement stmt = null;

            if (null == stmt) {
                stmt = conn.prepareStatement("SELECT * FROM `F1shopOnline`.`user` WHERE email='" + email + "';");
            }
            rset = stmt.executeQuery();

            String x = null;
            while (rset.next()) {
                x = rset.getString("name");


            }
            if (stmt != null) {
                stmt.close();
            }


            return x;

        } catch (SQLException e) {
            System.out.println("Error de MySQL: " + e.getMessage());
            return null;
        } catch (Exception e) {
            Logger.getLogger("user").log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());
            return null;
        } finally {
            if (rset != null) {
                try {
                    rset.close();
                } catch (SQLException e) {
                    Logger.getLogger("RecoverName").log(Level.SEVERE, "ERROR AL CERRAR RSET: " + e.getLocalizedMessage());
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    Logger.getLogger("RecoverName").log(Level.SEVERE, "ERROR AL CERRAR LA CONEXION: " + e.getLocalizedMessage());
                }
            }
        }
    }

    public void pay(Connection conn, String email, float price) throws SQLException {
        try {

            PreparedStatement stmt = null;

            if (null == stmt) {
                stmt = conn.prepareStatement("UPDATE `F1shopOnline`.`user` SET money=money-" + price + " WHERE email='" + email + "'");
            }

            stmt.executeUpdate();

            stmt.close();

        } catch (SQLException e) {
            System.out.println("Error de MySQL: " + e.getMessage());
        } catch (Exception e) {
            Logger.getLogger("Pago").log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());
            System.out.println("Error inesperado: " + e.getMessage());
        } finally {

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    Logger.getLogger("Pay").log(Level.SEVERE, "ERROR AL CERRAR LA CONEXION: " + e.getLocalizedMessage());
                }
            }
        }
    }

    public void purchases(Connection conn, String email) throws SQLException {
        try {
            PreparedStatement stmt = null;

            if (null == stmt) {
                stmt = conn.prepareStatement("UPDATE `F1shopOnline`.`user` SET purchases=purchases+1 WHERE email='" + email + "'");
            }

            stmt.executeUpdate();

            stmt.close();

        } catch (SQLException e) {
            System.out.println("Error de MySQL: " + e.getMessage());
        } catch (Exception e) {
            Logger.getLogger("Purchases").log(Level.SEVERE, "ERROR: " + e.getLocalizedMessage());
            System.out.println("Error inesperado: " + e.getMessage());
        } finally {

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    Logger.getLogger("Purchases").log(Level.SEVERE, "ERROR AL CERRAR LA CONEXION: " + e.getLocalizedMessage());
                }
            }
        }
    }

    /**
     * ************ DB *************************
     */
    /*
     * Funcion para sincronizacion, para que no puedan acceder dos con el mismo
     * email
     */
    public boolean equals(user c) {

        if (this.email.equals(c.getEmail())) {
            return true;
        } else {
            return false;
        }

    }
}
